package com.sskj.one.transaction;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import com.bulong.rudeness.RudenessScreenHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.one.MainPresneter;
import com.sskj.one.R;
import com.sskj.one.bean.PositionBean;
import com.sskj.one.component.DaggerUserDataComponent;
import com.sskj.one.transaction.adapter.PositionAdapter;
import com.sskj.one.util.ArithUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * @author Hey
 * Create at  2019/05/23
 */
public class PositionFragment extends BaseFragment<PositionPresenter> {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smartRefreshView)
    SmartRefreshLayout smartRefreshView;

    private BaseAdapter<PositionBean> adapter;
//    private PositionAdapter positionAdapter;

    private int page = 1;
    private int size = 20;

    private List<PositionBean> changeData = new ArrayList<>();

    private CompositeDisposable compositeDisposable;

    private int isCountDown;
    private DisposableSubscriber<Long> disposableSubscriber;

    private Map<Integer, double[]> times = new HashMap<>();

    private SparseArray<CountDownTimer> countDownCounters = new SparseArray<>();
    private String seventeen;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_position;
    }

    @Override
    public PositionPresenter getPresenter() {
        return new PositionPresenter();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (mPresenter != null) {
                mPresenter.getPositonRecord(true, page, size);
            }
        }
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        compositeDisposable = new CompositeDisposable();
        recyclerView.setLayoutManager(new LinearLayoutManager(App.INSTANCE));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(App.INSTANCE)
                .setPaintColor(Color.TRANSPARENT)
                .setPaintWidth((int) RudenessScreenHelper.dp2px(App.INSTANCE, 10))
                .setFirstDraw(true)
                .setLastDraw(true));

        adapter = new BaseAdapter<PositionBean>(R.layout.item_position, null, recyclerView, true) {
            @Override
            public void bind(ViewHolder holder, PositionBean item) {
//                Double fengkongPrice1 = null;//风控价1
//                Double fengkongPrice2 = null;//风控价2
//                Double fengkongPrice3 = null;//风控价3|
                TextView view = holder.getView(R.id.tv_count_down);
                TextView newRate = holder.getView(R.id.tv_new_rate);
                TextView fengkongRate = holder.getView(R.id.tv_feng_rate);
                holder.setText(R.id.tv_status, "1".equals(item.getOtype()) ? "买涨" : "买跌")
                        .setTextColor(R.id.tv_status, "1".equals(item.getOtype()) ?
                                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme))
                        .setText(R.id.tv_look_time, TimeFormatUtil.formatE(Long.valueOf(item.getAddtime()) * 1000))
                        .setText(R.id.tv_new_rate, NumberUtil.keep(item.getNowPrice(), 5))
                        .setText(R.id.tv_earn, Float.valueOf(item.getNowPrice()) < Float.valueOf(item.getBuyprice()) ? "$ 0.00000"
                                : "$ " + NumberUtil.keep((float) ArithUtil.mul(Double.valueOf(item.getLeverage()), Double.valueOf(item.getDeposit())), 5))
                        .setText(R.id.tv_xia_rate, item.getBuyprice())
                        .setText(R.id.tv_money, "$ " + NumberUtil.keep(item.getDeposit(), 5))
                        .setText(R.id.tv_count_down, item.getCycle_time() + "s");
                //计算最后3秒风控值
//                if (!isEmpty(seventeen)) {
//                    fengkongPrice3 = Double.valueOf(NumberUtil.keep(item.getSellprice3(), 5));
//                    if (Double.valueOf(seventeen) > fengkongPrice3) {
//                        double sub = ArithUtil.sub(Double.valueOf(seventeen), fengkongPrice3);
//                        try {
//                            fengkongPrice1 = ArithUtil.sub(Double.valueOf(seventeen), ArithUtil.div(sub, 3, 6));
//                            fengkongPrice2 = ArithUtil.sub(Double.valueOf(seventeen), ArithUtil.mul(ArithUtil.div(sub, 3, 6), 2));
//                        } catch (IllegalAccessException e) {
//                            e.printStackTrace();
//                        }
//                    } else if (Double.valueOf(seventeen) < fengkongPrice3) {
//                        double sub = ArithUtil.sub(fengkongPrice3, Double.valueOf(seventeen));
//                        try {
//                            fengkongPrice1 = ArithUtil.sub(fengkongPrice3, ArithUtil.mul(ArithUtil.div(sub, 3, 6), 2));
//                            fengkongPrice2 = ArithUtil.sub(fengkongPrice3, ArithUtil.div(sub, 3, 6));
//                        } catch (IllegalAccessException e) {
//                            e.printStackTrace();
//                        }
//                    } else if (Double.valueOf(seventeen).equals(fengkongPrice3)) {
//                        fengkongPrice1 = fengkongPrice3;
//                        fengkongPrice2 = fengkongPrice3;
//                    }
//                    times.put(view.hashCode(), new double[]{fengkongPrice1, fengkongPrice2, fengkongPrice3});
//                }
                //更新最后3秒风控值
                if (item.getFengkong_start().equals("1")) {
                    if (item.getCycle_time().equals("3")) {
                        newRate.setVisibility(View.GONE);
                        fengkongRate.setVisibility(View.VISIBLE);
                        fengkongRate.setText(NumberUtil.keep(item.getSellprice1(), 5));
//                        if (isEmpty(String.valueOf(times.get(view.hashCode())[0]))) {
//                        } else {
//                            fengkongRate.setText(NumberUtil.keep(String.valueOf(times.get(view.hashCode())[0]), 5));
//                        }
                    }
                    if (item.getCycle_time().equals("2")) {
                        newRate.setVisibility(View.GONE);
                        fengkongRate.setVisibility(View.VISIBLE);
                        fengkongRate.setText(NumberUtil.keep(item.getSellprice2(), 5));
//                        if (isEmpty(String.valueOf(times.get(view.hashCode())[1]))) {
//                        } else {
//                            fengkongRate.setText(NumberUtil.keep(String.valueOf(times.get(view.hashCode())[1]), 5));
//                        }
                    }
                    if (item.getCycle_time().equals("1")) {
                        newRate.setVisibility(View.GONE);
                        fengkongRate.setVisibility(View.VISIBLE);
                        fengkongRate.setText(NumberUtil.keep(item.getSellprice3(), 5));
//                        if (isEmpty(String.valueOf(times.get(view.hashCode())[2]))) {
//                        } else {
//                            fengkongRate.setText(NumberUtil.keep(String.valueOf(times.get(view.hashCode())[2]), 5));
//                        }
                    }
                }
                if (isCountDown == 0) {
//                    CountDownTimer countDownTimer = countDownCounters.get(view.hashCode());
//                    if (countDownTimer != null) {
//                        //将复用的倒计时清除
//                        countDownTimer.cancel();
//                    }
//                    if (Long.valueOf(item.getCycle_time()) > 0) {
//                        if (Long.valueOf(item.getCycle_time()) > 0) {
//                            countDownTimer = new CountDownTimer(Long.valueOf(item.getCycle_time()) * 1000, 1000) {
//                                @Override
//                                public void onTick(long l) {
//                                    if ((l - 1000) / 1000 == 2) {
//                                        newRate.setVisibility(View.GONE);
//                                        fengkongRate.setVisibility(View.VISIBLE);
//                                        fengkongRate.setText(NumberUtil.keep(item.getSellprice1(), 5));
//                                    }
//                                    if ((l - 1000) / 1000 == 1) {
//                                        newRate.setVisibility(View.GONE);
//                                        fengkongRate.setVisibility(View.VISIBLE);
//                                        fengkongRate.setText(NumberUtil.keep(item.getSellprice2(), 5));
//                                    }
//                                    if ((l - 1000) / 1000 == 0) {
//                                        newRate.setVisibility(View.GONE);
//                                        fengkongRate.setVisibility(View.VISIBLE);
//                                        fengkongRate.setText(NumberUtil.keep(item.getSellprice3(), 5));
//                                    }
//                                    view.setText((l - 1000) / 1000 + "s");
//                                }
//
//                                @Override
//                                public void onFinish() {
//                                    view.setText("0s");
//                                    adapter.remove(adapter.getData().indexOf(item));
//                                }
//                            }.start();
//                            countDownCounters.put(view.hashCode(), countDownTimer);
//                        } else {
//                            view.setText("0s");
//                        }


//                        disposableSubscriber = new DisposableSubscriber<Long>() {
//                            @Override
//                            public void onNext(Long aLong) {
//                                Log.i(TAG, "onNext: " + aLong);
//                                holder.setText(R.id.tv_count_down, Long.valueOf(item.getCycle_time()) - aLong + "s");
//                                if (Long.valueOf(item.getCycle_time()) - aLong - 1 == 2) {
//                                    newRate.setVisibility(View.GONE);
//                                    fengkongRate.setVisibility(View.VISIBLE);
//                                    fengkongRate.setText(NumberUtil.keep(item.getSellprice1(), 5));
//                                }
//                                if (Long.valueOf(item.getCycle_time()) - aLong - 1 == 1) {
//                                    newRate.setVisibility(View.GONE);
//                                    fengkongRate.setVisibility(View.VISIBLE);
//                                    fengkongRate.setText(NumberUtil.keep(item.getSellprice2(), 5));
//                                }
//                                if (Long.valueOf(item.getCycle_time()) - aLong - 1 == 0) {
//                                    newRate.setVisibility(View.GONE);
//                                    fengkongRate.setVisibility(View.VISIBLE);
//                                    fengkongRate.setText(NumberUtil.keep(item.getSellprice3(), 5));
//                                }
////                                if (Long.valueOf(item.getCycle_time()) - aLong-1 == 0) {
////                                    holder.setText(R.id.tv_count_down, "0s");
////                                    mPresenter.getPositonRecord(true, page, size);
////                                    adapter.setNewData(new ArrayList<>());
////                                }
//                            }
//
//                            @Override
//                            public void onError(Throwable t) {
//
//                            }
//
//                            @Override
//                            public void onComplete() {
//                                holder.setText(R.id.tv_count_down, "0s");
//                                adapter.remove(adapter.getData().indexOf(item));
////                                adapter.notifyItemRangeChanged(holder.getLayoutPosition(), 1);
////                                adapter.remove(holder.getAdapterPosition());
//                                page = 1;
////                                mPresenter.getPositonRecord(true, page, size);
//                            }
//                        };
//                        compositeDisposable.add(disposableSubscriber);
//                        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
//                                .take(Long.valueOf(item.getCycle_time()) + 1)
//                                .observeOn(AndroidSchedulers.mainThread())
//                                .subscribe(disposableSubscriber);
//                } else {
//                    holder.setText(R.id.tv_count_down, "0s");
//                }
                }
            }
        }

        ;
    }


    @Override
    public void initData() {
        mPresenter.getPositonRecord(true, page, size);
        smartRefreshView.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getPositonRecord(false, page, size);
        });
        smartRefreshView.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mPresenter.getPositonRecord(false, page, size);
        });

        Observable.interval(0, 1, TimeUnit.SECONDS)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new Observer<Long>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (adapter != null && adapter.getData().size() > 0) {

                            for (PositionBean p : adapter.getData()) {
                                String cycle_time = p.getCycle_time();
                                if (p.getCycle_time().equals("0")) {
                                    adapter.getData().remove(p);
                                }
                                p.setCycle_time((Integer.valueOf(cycle_time) - 1) + "");
                            }
                            adapter.notifyDataSetChanged();
//                            Iterator<PositionBean> iterator = adapter.getData().iterator();
//                            while (iterator.hasNext()) {
//                                PositionBean positionBean = iterator.next();
//                                String cycle_time = positionBean.getCycle_time();
//                                positionBean.setCycle_time((Integer.valueOf(cycle_time) - 1) + "");
//                                changeData.add(positionBean);
//                            }
//                            adapter.setNewData(changeData);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(CoinBean data) {
        if (data.getCode().equals("USDCNY") && adapter.getData().size() > 0) {
            for (PositionBean p : adapter.getData()) {
                p.setNowPrice(data.getPrice());
            }
            isCountDown = 1;
            adapter.notifyDataSetChanged();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void seventeen(String price) {
        seventeen = price;
    }


    public static PositionFragment newInstance() {
        PositionFragment fragment = new PositionFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }

    public void getDataOK(List<PositionBean> data) {
        if (data == null) {
            return;
        }
        Iterator<PositionBean> iterator = data.iterator();
        while (iterator.hasNext()) {
            PositionBean positionBean = iterator.next();
            if (positionBean.getCycle_time().equals("0"))
                iterator.remove();   //注意这个地方
        }
        if (page == 1) {
            adapter.setNewData(data);
        } else {
            if (data.size() < size) {
                smartRefreshView.finishLoadMoreWithNoMoreData();
            } else {
                smartRefreshView.finishLoadMore();
                adapter.addData(data);
            }
        }


    }

    public void stopRefresh() {
        if (smartRefreshView != null && smartRefreshView.isRefreshing()) {
            smartRefreshView.finishRefresh();
        }
    }

    public Observable<Long> time(Long time) {
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(time + 1)
                .compose(RxSchedulersHelper.io_main())
                .map(aLong -> time - aLong);
    }

}
